import { ref } from "vue";
import { getCurrencyRate } from "@/services/apiGetCurrency";
export function useCurrencyConvert(isFirst, showPicker) {
  const firstLabel = ref("CNY");
  const firstAmount = ref();
  const secondLabel = ref("USD");
  const secondAmount = ref();
  const isLoading = ref(false);

  async function convert(flag) {
    isLoading.value = true;
    console.log('before',isLoading.value);

    console.log(flag);
    if (flag === "first") {
      const amount = await getCurrencyRate(
        firstLabel.value.toLowerCase(),
        secondLabel.value.toLowerCase(),
        firstAmount.value
      );
      secondAmount.value = Number(amount.toFixed(2));
      isLoading.value = false;
      console.log('after',isLoading.value);
      return;
    } else {
      const amount = await getCurrencyRate(
        secondLabel.value.toLowerCase(),
        firstLabel.value.toLowerCase(),
        secondAmount.value
      );
      firstAmount.value = Number(amount.toFixed(2));
      isLoading.value = false;
      console.log('after',isLoading.value);
    }
  }

  const onConfirm = ({ selectedOptions }) => {
    showPicker.value = false;
    if (isFirst.value) {
      firstLabel.value = selectedOptions[0].text;
    } else {
      secondLabel.value = selectedOptions[0].text;
    }
    if (firstLabel.value === secondLabel.value) {
      if (isFirst.value) {
        secondAmount.value = firstAmount.value;
      } else {
        firstAmount.value = secondAmount.value;
      }
      return;
    }
    convert(isFirst.value ? "first" : "second");
  };

  return {
    firstLabel,
    firstAmount,
    secondLabel,
    secondAmount,
    isLoading,

    convert,
    onConfirm,
  };
}
